<template>
  <div class="product-list">
    <el-card class="box-card product-list-card" shadow="never">
      <div slot="header" class="clearfix">
        <CardHeader> </CardHeader>
      </div>
      <CardinputVue :text="'请输入搜索信息'"></CardinputVue>
    </el-card>
    <el-card class="box-card product-list-card" shadow="never">
      <div slot="header" class="clearfix">
        <CardDate @add="add()"></CardDate>
      </div>
      <el-table :data="tableData" class="type-table" height="325" border style="width: 100%">
        <el-table-column prop="banner_id" label="编号" align="center" width="100"></el-table-column>
        <el-table-column prop="product_name" label="商品名称" align="center" width="150"></el-table-column>
        <el-table-column label="轮播图" align="center">
          <template slot-scope="scope">
            <el-image v-if="scope.row.banner_url" :src='scope.row.banner_url' fit="fit"
              style="height: 100px; width: 275px;" />
          </template>
        </el-table-column>
        <el-table-column label="商品链接" align="center" width="300">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.product_url" class="item" effect="dark" placement="bottom"
              :content="scope.row.product_url">
              <el-link type="warning" :href="'http://localhost:8080/#/ProductList'"><i
                  class="el-icon-view el-icon--right" />
                查看商品</el-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="openChange(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" slot="reference"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <el-dialog title="编辑商品轮播图信息" class="chang-product" :close-on-click-modal="false" :visible.sync="dialogFormVisible"
      center>
      <el-form class="info-form" inline :rules="alterRules" :model="alterForm" ref='changeFrom'>
        <el-form-item label="商品名称：" prop="product_name" style="width: 100%">
          <el-input size="small" v-model="alterForm.product_name" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品链接：" prop="product_url" style="width: 100%">
          <el-input size="small" autosize v-model="alterForm.product_url" placeholder="商品购买页链接"></el-input>
        </el-form-item>
        <el-form-item label="商品图片：" prop="banner_url" style="width: 100%;">
          <el-upload ref="upload" class="product-upload" action="http://127.0.0.1:3000/api/upload"
            :on-success="uploadSuccess" :drag="true" list-type="picture" :limit="1" :auto-upload="false"
            style="display: flex;justify-content: center;align-items: center; " :on-exceed="handleExceed">
            <el-image v-if="alterForm.banner_url" :src="alterForm.banner_url"
              style="height: 140px;width: 160px"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" style="padding: 12px 43px;margin: 0 30px;" @click="submitChange('changeFrom')">确
          定</el-button>
        <el-button style="padding: 12px 43px;margin: 0 30px;" @click="cancelChange('changeFrom')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getBanner, showPageBanner, deletsBanner, addBanner, updataBanner } from '@/api';
import CardDate from '@/components/commodity/CardDate.vue';
import CardHeader from '@/components/commodity/CardHeader.vue';
import CardinputVue from '@/components/commodity/Cardinput.vue';
export default {
  name: 'KodaiOrderList',

  data () {
    return {
      tableData: [],
      dialogFormVisible: false,
      insert: false,   //插入时的标志,
      alterForm: {
        banner_id: '',
        product_name: '',
        product_url: '',
        banner_url: ''
      },
      alterRules: {
        product_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 1, max: 30, message: '名称长度不允许超过 30 个字符', trigger: 'blur' }],
        product_url: [{ required: true, message: '请输入商品购买页面链接', trigger: 'blur' },
        { min: 1, max: 100, message: '商品链接长度不允许超过 200 个字符', trigger: 'blur' }],
      },
      total: 20,
      queryParams: {
        pageNum: 1,
        pageSize: 2
      },
    };
  },
  mounted () {
    getBanner().then(res => {
      this.total = res.data.data.length
      this.getList();
    })
  },
  methods: {
    // 添加函数
    add () {
      this.dialogFormVisible = true;
      this.insert = true
      this.alterForm = {
        banner_id: '',
        product_name: '',
        product_url: '',
        banner_url: ''
      }
    },
    // 编辑函数
    openChange (index, row) {
      this.dialogFormVisible = true
      this.alterForm = row
    },
    // 删除函数
    handleDelete (index, row) {
      this.$confirm('此操作将永久删除该品牌信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        zIndex: 3000
      }).then(() => {
        let loading = this.$loading({ lock: true, text: "正在提交数据...", background: "rgba(255,255,255,0.1)" });
        deletsBanner(row).then(res => {
          loading.close();
          if (res.data.code === 200) {
            this.$router.go(0)
            this.$notify({ title: '成功', message: '轮播图(' + row.product_name + ')\t移除成功', type: 'success', duration: 3000, position: 'top-right' });
          } else {
            this.$notify({ title: '错误', message: res.data.msg, type: 'error', duration: 3000, position: 'top-right' });
          }
        }).catch((err) => {
          loading.close();
          this.$message.error(err);
        })
      }).catch((err) => {
          
        })
    },
    // 提交函数
    submitChange (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.$refs.upload.submit();

          setTimeout(() => {
            if (this.insert) {
              this.alterForm.banner_id = this.generateBannerId()
              console.log(this.alterForm.banner_id);
              addBanner(this.alterForm).then(res => {
                if (res.data.code === 200) {
                  this.dialogFormVisible = false;
                  this.$router.go(0)
                  this.$notify({ title: '成功', message: this.alterForm.product_name + '\t轮播图添加成功', type: 'success' });
                }
              }).catch(() => {
                this.$notify({ title: '轮播图添加失败', type: 'error' });
              });
            } else {
              updataBanner(this.alterForm).then(res => {
                if (res.data.code === 200) {
                  this.dialogFormVisible = false;
                  this.$router.go(0)
                  this.$notify({ title: '成功', message: this.alterForm.product_name + '\t轮播图修改成功', type: 'success' });
                }
              }).catch(() => {
                this.$notify({ title: '错误', type: 'error' });
              });
            }
          }, 1000)
        } else {
          return false;
        }
      })
    },
    // 上传图片函数
    uploadSuccess (res, file) {
      if (res.code === 200) {
        this.showMessage.call(this, 'success', "轮播图图片上传成功！");
        this.alterForm.banner_url = res.url;
        this.$refs['upload'].clearFiles();
      } else {
        this.showMessage.call(this, 'error', "轮播图图片上传失败！");
      }
    },
    // 文件数量过多时提醒
    handleExceed () {
      this.showMessage.call(this, 'error', "最多支持1个附件上传");
    },
    cancelChange (formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
      this.$notify({ title: '操作取消', message: '', type: 'success' });
    },
    // 分页组件函数
    async getList () {
      // 显示加载动画
      let loading = this.$loading({ lock: true, text: "加载中", background: "rgba(0, 0, 0, 0.7)" });
      try {
        var res = await showPageBanner(this.queryParams)
        if (res.data.code == 200) {
          this.tableData = res.data.data
        }
      }
      catch (err) {
        // 显示注册失败的消息，并提示错误原因
        this.showMessage.call(this, 'error', '查询失败');
      }
      finally {
        // 关闭加载动画
        loading.close();
      }
    },
    // 随机生成编号
    generateBannerId () {
      const timestamp = Date.now().toString();
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      return `B${timestamp}${randomNum}`;
    }
  },
  components: {
    CardDate, CardHeader, CardinputVue
  }
};
</script>

<style lang="scss" scoped>
input[type="file"]::file-selector-button {
  font-weight: 500;
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  // 各种属性
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.box-card ::v-deep .el-card__header {
  padding: 0px 10px;
}
</style>
